package com.googlecode.dtools.typeinfo.graphviz.format.impl;

import com.googlecode.dtools.typeinfo.graphviz.bean.DmLink;
import com.googlecode.dtools.typeinfo.graphviz.format.Formatter;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 *
 * @author A_Reshetnikov
 * @since Date: 23.05.12 Time: 13:38
 */
public class FormatterImpl implements Formatter {

    private static String head = "<graphviz dot>\n" +
            "digraph x {\n" +
            "rankdir = \"LR\";\n" +
            "node [fontsize=10];\n" +
            "overlap=false;\n\n";
    private static String end = "\n}\n</graphviz>";
    private int maxCountForSaveGraphvizSpace= 100;

    public String format(String typeName, Set<DmLink> col) {
        String res = head;
        res += formatTypeNamesStyle(typeName, col);
        for (DmLink dmLink : col) {
            res += format(typeName, dmLink) + "\n";
        }
        return res + end;
    }

    private String formatTypeNamesStyle(String typeName, Set<DmLink> col) {
        String res = "";
        Set<String> typeNames = new HashSet<String>();
        for (DmLink dmLink : col) {
            typeNames.add(dmLink.getParent());
            typeNames.add(dmLink.getChild());
        }
        typeNames.remove(typeName);
        res += typeName + " [fillcolor=lightpink, style=filled, shape=box]\n";
        if (col.size() <= maxCountForSaveGraphvizSpace) {
            for (String t : typeNames) {
                res += t + "[shape=box]\n";
            }
        }
        return res;
    }

    private String format(String typeName, DmLink dmLink) {
        String linkName;
        if (dmLink.getParent().equals(typeName))
            linkName = dmLink.getName();
        else
            linkName = String.format("%s.%s", format2Prefix(dmLink.getParent()), dmLink.getName());
        return String.format("%s -> \"%s\" -> %s", dmLink.getParent(), linkName, dmLink.getChild());
    }

    private String format2Prefix(String parent) {
        String res = "";
        String[] array = parent.split("_");
        for (String anArray : array) {
            res += anArray.substring(0, 1);
        }
        return res;
    }

    public void setMaxCountForSaveGraphvizSpace(int maxCountForSaveGraphvizSpace) {
        this.maxCountForSaveGraphvizSpace = maxCountForSaveGraphvizSpace;
    }
}
